#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <ctype.h>

#define IP_SIZE 32

void PrintUsage()
{
	printf("Usage: ./fork_exec (eth0|wlan0)\n") ;
	return ;
}


int main(int argc, char **argv)
{

	pid_t   pid ;
	int     fd ;
	char    buf[128] ;
	char    ip[IP_SIZE] ;
	char    *ptr ;			        
	char    *ip_start ;	
	char    *ip_end ;
	FILE    *pfd ;

	if( argc<2 )
	{
		PrintUsage() ;
		return 0 ;
	}

	fd = open("ifconfig.log", O_RDWR|O_CREAT|O_TRUNC, 0666) ;

	if(fd < 0)
	{
		printf("open file failure:%s", strerror(errno)) ;	
		return -1 ;
								
	}
	
	pid = vfork() ;
	if( pid < 0 )
	{
		printf("Create PID failure: %s\n", strerror(errno)) ;
		return -2 ;

	}


	else if(pid == 0)       // Child process
	{

		printf("Child process is running...\n") ;

		dup2(fd, STDOUT_FILENO) ;

		execl("/sbin/ifconfig", "ifconfig", argv[1], NULL) ;
		printf("If child return there, execl() failed\n") ;
		return -3 ;
	}
														        
	else                    // Parent process
	{
		printf("Parent procee is running...\n") ;
		sleep(3) ;
	}
	
	memset(buf, 0, sizeof(buf)) ;
	pfd = fdopen(fd,"r") ;
	fseek(pfd, 0, SEEK_SET);
	while( fgets(buf,sizeof(buf),pfd) )
	{	
		if( ( ptr = strstr(buf, "inet") ) )
			break ;
	}
																

	ptr = ptr + strlen("inet") ;
	

	while( isblank(*ptr) )	
		ptr++ ;

	ip_start = ptr;



	while( !isblank(*ptr) )
		ptr++ ;

	ip_end = ptr ;


	memcpy(ip, ip_start, (ip_end - ip_start) ) ;

	printf("IP_ADDRESS: %s\n", ip) ;

	return 0 ;
}
